<script>
import VueRouter from 'vue-router'
export default {
  name:"userManage",
  data() {
    return {
      tableData: [],
      pageNum:1,
      pageSize:5,
      total:5,
      name:'',
      type:'',
      telephone:'',
      dialogVisible:false,
      loading: true,
      form:{
        id:'',
        name:'',
        contacts:'',
        email:'',
        description:'',
        type:'',
        telephone:'',
        address:'',
        status:''
      },
      rules: {
        loginName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        telephone: [
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输⼊正确的⼿机号码", trigger: "blur"}
        ],
      }
    };
  },
  methods:{
    loadPost(){
      this.loading = true;
      this.$axios.post('/zzh-user/list',{
        page:this.pageNum,
        limit:this.pageSize,
        name:this.name,
        telephone:this.telephone,
        type:this.type
      }).then(res=>res.data).then(res=>{
        this.loading = false;
        if(res.resultCode==200){
          this.tableData=res.data
          this.total=res.total
        }else {
          alert('获取数据失败')
        }
      })
    },
    //导出数据
    exportExcel() {
      //将响应数据类型设置为 Blob 对象   原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用，因为你可以直接将返回的二进制数据用于创建可下载的文件
      this.$axios.post('/zzh-excel/userExcel',this.tableData, { responseType: 'blob' })
          .then(response => {
            // 将获取到的Excel数据转换为文件
            //Blob是二进制的容器，可以存放任意类型的二进制文件：图片/音频/文件
            //type : 类型设为Excel文件（.xlsx）的MIME类型，告诉浏览器创建的是一个Excel文件，默认使用excel打开
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // 创建隐藏的下载链接并模拟点击下载
            const link = document.createElement('a');
            //创建一个可供用户下载的链接
            link.href = URL.createObjectURL(blob);
            link.download = '用户信息表格.xlsx';
            //设置链接的打开方式为新标签页（_blank），这样用户点击链接后会在新标签页中下载文件
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => {
            console.error(error);
          });
    },
    add(){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    loadAdd(){
      //表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.id){
            this.doUpdate();
          }else {
            console.log("doAdd")
            this.doAdd()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    doAdd(){
      this.$axios.post('/zzh-user/add',this.form).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '新增数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '新增数据失败',
            type: 'error'
          });
        }
      })
    },
    mod(row){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.form.id=row.id
        this.form.name=row.name
        this.form.contacts=row.contacts
        this.form.email=row.email
        this.form.type=this.type
        this.form.description=row.description
        this.form.telephone=row.telephone
        this.form.address=row.address
      })
    },
    doUpdate(){
      this.$axios.put('/zzh-user/update',this.form).then(res=>res.data).then(res=>{
        this.form.id=""
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '更新数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新数据失败',
            type: 'error'
          });
        }
      })
    },
    del(id){
      this.$axios.delete('/zzh-user/delete?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    },
    updateStatus(id){
      this.$axios.put('/zzh-user/updateStatus?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '更新状态成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新状态失败',
            type: 'error'
          });
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    resetParam(){
      this.name=''
      this.telephone=''
      this.loadPost()
    },
    resetForm() {
      //重置窗体
      this.$refs.form.resetFields();
    },
    setTypeFromRoute() {
      if (this.$route.path === '/SupplierManage') {
        this.type = '供应商';
      } else if (this.$route.path === '/UserManage') {
        this.type = '客户';
      }
      this.form.type=this.type
    }
  },
  beforeMount() {
    console.log(this.$route.path)
    this.setTypeFromRoute(this.$route.path);
    console.log(this.type)
    this.loadPost();
  },
  beforeRouteUpdate(to, from, next) {
    this.setTypeFromRoute(to.path);
    next();
  },
  mounted() {
    this.setTypeFromRoute(this.$route.path);
  },
  watch: {
    '$route.path'(newPath) {

      if (newPath === '/SupplierManage') {
        this.type = '供应商';
      } else if (newPath === '/UserManage') {
        this.type = '客户';
      }
    }
  },
}
</script>

<template>
  <div>
    <!--    按钮-->
    <div style="margin-bottom: 5px">
      名称：
      <el-input v-model="name" placeholder="请输入名称查询" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      手机号码：
      <el-input v-model="telephone" placeholder="请输入手机号码查询" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>

      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
    </div>
    <!--    表单-->
    <el-table :data="tableData" v-loading="loading"
              :header-cell-style="{background:'#f3f6fd',color:'#555'}">
      <el-table-column prop="id" label="id" width="140">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="140">
      </el-table-column>
      <el-table-column prop="contacts" label="联系人" width="120">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="120">
      </el-table-column>
      <el-table-column prop="telephone" label="电话号码" width="120">
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="120">
      </el-table-column>
      <el-table-column prop="description" label="备注" width="120">
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              disable-transitions>{{scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '禁用' : '已删除'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left: 5px;margin-right: 5px"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="success" @click="updateStatus(scope.row.id)">启用/禁用</el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!--    提示框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人：" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱：" prop="email">
          <el-input v-model="form.email"  placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="description">
          <el-input v-model="form.description" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="类型：" prop="type" v-show="false">
          <el-input v-model="form.type" placeholder="请输入类型"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="loadAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>